import base64
import re

import requests

username = 'script'
password = '123456a.'

# bct服务
# bct_url = "http://10.1.6.61"
bct_url = "http://10.1.6.22"
# bct_url = "http://10.80.54.168"

def _get_token(auth_username: str, auth_password: str, server_url: str,
               base64_encode: bool = True) -> str:
    auth_url = "%s%s" % (server_url, '/api/auth-service/users/login')

    if base64_encode:
        usr_name = base64.b64encode(auth_username.encode())
        usr_pwd = base64.b64encode(auth_password.encode())
    else:
        usr_name = auth_username
        usr_pwd = auth_password

    auth_body = {
        'userName': usr_name.decode(),
        'password': usr_pwd.decode()
    }
    headers = {}
    auth = requests.post(auth_url, json=auth_body, headers=headers)
    try:
        _token = auth.json()['token']
        return _token
    except Exception:
        error_message = auth.json()['errorMessage']
        raise ValueError(error_message)


def delete_attach():
    token = _get_token(username, password, bct_url)
    headers = {"Authorization": "Bearer " + token
               }
    auth = requests.post('http://10.1.6.22/bct/attachment-service/attachment/delete?id=1572455256575639552',  headers=headers)
    print(auth.json())


def update_attach():
    file_path = 'C:\\Users\\summit\\Desktop\\收益凭证\\11.docx'
    file = {
        "file": ('22.docx', open(file_path, 'rb'), "multipart/form-data")
    }
    data1 = {'type': 'OTHER'}
    token = _get_token(username, password, bct_url)
    headers = {"Authorization": "Bearer " + token }
    auth = requests.post('http://10.1.6.22/bct/attachment-service/attachment/upload',files=file, data=data1, headers=headers)
    print(auth.json())

if __name__ == '__main__':
    #delete_attach()
    update_attach()
